// packageC/pages/takeOutIndex/takeOutIndex.js
const app = getApp()
const common = require('../../../public.js')
Page({

    /**
     *   页面的初始数据
     */
    data: {
        hasBuy:false,
        cardVipJson:"",
        postPrice:0.00,
        standardType:false,
        getHasSelectShopItemIdAndCountList:[],// 全部食物赋个数专用
        rightShopCount:0,
        leftBadgeList:[],
        allAttrValueList:[],
        oneId:null,

        value: 5,
        shopCarShow: false,
        userInfo: {},
        orderList: ['点餐', '评价', '商家', '攻略'],
        actIndex: 0,
        cateLeftList: [], //左边列表
        defaultItemList: [],
        activeId: -1, //左边s
        toView: '', //滚动目标f
        isCollected: false,
        clickShow: false,//监听左侧菜单栏是否点击
        guigeShow: false, //规格
        okHeight: 0,
        showImg: false,
        pageNum: 1,
        showStoreCoupons: false,
        isLoadingBusy: false, // 标记是否正在加载更多数据
        storeCouponsList: [], //店铺优惠券列表
        canLoad: true,
        flagHeight:true,
        isLoadingBusy: false,
        selectImg:'http://feiyangimage.oss-cn-shanghai.aliyuncs.com/wxApplets/icon/collect_icon_select.png',
        notselectImg:'http://feiyangimage.oss-cn-shanghai.aliyuncs.com/wxApplets/icon/collect_icon.png'
    },
    click_album(e){
       let currentIndex = e.currentTarget.dataset.index
       wx.navigateTo({
         url: '/packageA/pages/photoAlbum/photoAlbum?arr='+ JSON.stringify(this.data.shopInfo.backUpPicList) 
          + '&currentIndex=' + currentIndex
         ,
       })
    },
    //  去详情页
    toDetail(e) {
        console.log('22222');
        // console.log(e.currentTarget.dataset.item, "jjjjooooo")
        let item = JSON.stringify(e.currentTarget.dataset.item)
        wx.navigateTo({
            url: '/pages/coupons/useCoupons/index?&from=company' + '&item=' + item,
        })
    },
    receiveStoreConpons(e) {
        let that = this
        let {
            couponid
        } = e.currentTarget.dataset
        let tempJson = {
            userId: that.data.userInfo.id,
            discountCouponId: couponid,
            source: 1, // 1为手动领取，2为系统群发
            token: that.data.token
        }
        common.post("/discountCoupon/getShopCoupon", tempJson, function (res) {
            if (res.status == 200) {
                wx.showToast({
                    title: '领取成功',
                    icon: "none"
                })
                that.setData({
                    storeCouponsList: []
                }, () => {
                    that.getStoreCoupons(that.data.storeId, true)
                })

            } else {
                wx.showToast({
                    title: res.msg ? res.msg : '领取失败',
                    icon: "none"
                })
            }
        })
    },
    // 店铺优惠券列表
    getStoreCoupons(refresh = true) {
        const that = this
        if (refresh) {
            this.data.canLoad = true
        }
        if (that.data.canLoad) {  //可以加载
            if (!refresh && this.data.isLoadingBusy) {
                return
            }
            this.setData({
                isLoadingBusy: true
            })
            const params = {
                storeId: that.data.storeId,
                pageNum: refresh ? 1 : that.data.pageNum + 1,
                status: 4
            }
            common.post("/discountCoupon/showDiscoutCouponList", params, function (res) {
                if (res.status === 200) {
                    that.data.pageNum = params.pageNum
                    if (res.data.result_list != '' || res.data.result_list.length != 0) {
                        that.setData({
                            storeCouponsList: [...that.data.storeCouponsList, ...res.data.result_list],
                        })
                    } else {
                        if (that.data.pageNum == 1) {
                            that.setData({
                                storeCouponsList: []
                            })
                            return
                        }
                        that.setData({
                            canLoad: false,
                        })
                    }

                }
            }, function () {
                that.setData({
                    isLoadingBusy: false
                })
            })
        }

    },
    to_coupfn() { this.setData({ showStoreCoupons: true }) },
    // 电话
    callPhone() {
        wx.makePhoneCall({
            phoneNumber: this.data.shopInfo.store.mobile,
            fail: function () { }
        })
    },
    checkAddress() { //点击地址按钮
        if (!this.data.shopInfo.store.xpoint || !this.data.shopInfo.store.ypoint) {
            common.showToast('商家未设置位置信息')
            return
        }
        let lon = parseFloat(this.data.shopInfo.store.xpoint)
        let lat = parseFloat(this.data.shopInfo.store.ypoint)
        wx.openLocation({
            latitude: lat,
            longitude: lon,
            name: this.data.shopInfo.store.name ? this.data.shopInfo.store.name : null,
            address: this.data.shopInfo.store.address ? this.data.shopInfo.store.address : null,
            scale: 18,
            fail: () => {
                wx.showToast({
                    title: '无地址信息',
                    icon: 'none'
                })
            }
        })
    },
    // 触底效果
    fnLower(e) {
        this.gong(false)
    },
    gong(refresh = false) {
        const that = this
        if (this.data.isLoadingBusy) {
            return
        }
        const pageNum = refresh ? 1 : this.data.pageNum + 1
        let tempJson = {
            pageSize: 10,
            pageNum,
            storeId: this.data.storeId
        }
        common.post('/storeArticle/getStoreArticleListForOneStore', tempJson,
            function (res) {
                that.data.pageNum = pageNum
                if (res.status === 200) {
                    that.setData({
                        articleList: res.data.list,
                        articleLists: refresh ? res.data.list : [...res.data.list, ...that.data.articleLists]
                    }, () => {
                        that.stopFn(res)
                    })
                } else {
                    // common.showRequestErrMsg(res)
                    that.stopFn(res)
                }
            },
            function () {
                // that.setData({
                //     isLoadingBusy: false
                // })
            })
    },
    // 没有数据不掉接口
    stopFn(res) {
        const that = this
        if (res.data && res.data.list !== []) {
        } else {
            that.setData({
                isLoadingBusy: true
            })
        }
    },
    // 图片预览
    preview(event) {
        let { nindex, windex } = event.currentTarget.dataset
        console.log(nindex, windex)
        let pic_ce = this.data.commentList[windex].picUrls
        this.setData({
            pic_ce,
            current: nindex,
            showImg: true
        })
    },
    goDetails(e) {
        return;
        let itemId = e.currentTarget.dataset.item.id
        wx.navigateTo({
            url: `/packageC/pages/takeoutDetail/takeoutDetail?itemId=${itemId}&storeId=${this.data.storeId}`,
        })

    },

    // getLeftBadgeNum(flag = false) {
    //     const that = this
    //     let tempJson = {
    //         storeId: that.data.storeId,
    //         userId: that.data.userInfo.id,
    //         token: that.data.token
    //     }
    //     common.wxRequest('/cart/listByStore', 'post', tempJson, 'application/x-www-form-urlencoded', function (res) {
    //         if (res.status === 200) {
    //             // let totalPrice = 0;
    //             // let totalNum = res.data.totalNum
    //             // res.data.list.map((item, index) => {
    //             //     totalPrice = item.num * item.price + totalPrice
    //             // })
    //             console.log('aaaa处理后---',res.data);
                
    //             that.setData({
    //                 leftBadgeList: res.data.list,
    //                 // cartNum: totalNum,
    //                 // goodsCount: 1,
    //                 // totalPrice
    //             },()=>{
    //                 that.shopInfo()
    //                 that.getUserSelectInfo();
    //             })

    //         } else {
    //             that.shopInfo()
    //             that.getUserSelectInfo();
             

    //         }
    //     }, () => {
    //         that.setData({
    //             isShowLoader: false  //购物车加载
    //         })
    //     })
    // },
    // 获取购物车数量
    getCartNum(flag = false) {
        const that = this
        let tempJson = {
            storeId: that.data.storeId,
            userId: that.data.userInfo.id,
            token: that.data.token
        }
        common.wxRequest('/cart/listByStore', 'post', tempJson, 'application/x-www-form-urlencoded', function (res) {
            if (res.status === 200) {
                let totalPrice = 0;
                let totalNum = res.data.totalNum
                res.data.list.map((item, index) => {
                    totalPrice = item.num * item.price + totalPrice
                })
                console.log('处理后---',res.data);
                that.setData({
                    cartList: res.data.list,
                    cartNum: totalNum,
                    goodsCount: 1,
                    totalPrice
                },()=>{
                    console.log('价格---',that.data.totalPrice);
                })

            } else {
                that.setData({
                    cartList: [],
                    cartNum: 0,
                    goodsCount: 1,
                    totalPrice: 0
                })
                if (!flag) {
                    wx.showToast({
                        icon: 'none',
                        title: res.msg ? res.msg : '添加失败',
                    })
                }

            }
        }, () => {
            that.setData({
                isShowLoader: false  //购物车加载
            })
        })
    },
    // 获取左边类目及个数、右边列表、给历史选中增加selectNum和selectCardId属性
    getUserSelectInfo(tempItem,type){
        
        var that = this
        var tempJson = {
            storeId: that.data.storeId,
            xpoint: this.data.lat,
            ypoint: this.data.lon,
            token: that.data.token,
            userId: that.data.userInfo.id,
        }
        common.get('/store/getStoreClassifyListAndAllItemForUser', tempJson, res => {
            console.log('ccc返回内容为--',res,'----getHasSelectShopItemIdAndCountList',this.data.getHasSelectShopItemIdAndCountList);
            var dealList = res.data.defaultItemList;
            for(var i = 0;i < dealList.length;i++){// 给历史选中增加selectNum和selectCardId属性
                var allItem = dealList[i];
                for(var j = 0;j < this.data.getHasSelectShopItemIdAndCountList.length;j++){
                    var selectItem = this.data.getHasSelectShopItemIdAndCountList[j];
                    console.log('----selectItem---',selectItem.itemId);
                    if(selectItem.itemId == allItem.id){
                        allItem.selectNum = selectItem.num;
                        allItem.selectCardId = selectItem.id;
                    }
                }
            }
            console.log('处aaa理后---',dealList);

            var tempList = res.data.storeCatList;
            console.log('主页里---',tempList);
            console.log('角标i里---',this.data.leftBadgeList);
            // for(var i = 0;i<tempList.length;i++ ){
            //     for(var j = 0;j < this.data.leftBadgeList.length;j++){
            //         if(parseInt(this.data.leftBadgeList[j].storeCid)==tempList[i].id){
            //             tempList[i].num = this.data.leftBadgeList[j].num;
            //         }
            //     }
            // }
            console.log('aaa主页里---',tempList);
            this.setData({
                cateLeftList:tempList,
                defaultItemList: dealList,
            }, () => {
                // if(type=='minus'){ // 已经通过/cart/updateOneByCartId和/cart/add接口删除或添加商品，不需要再执行如下注释的代码
                //     that.minusFinalFunc(tempItem);
                // }else if(type=='add'){
                //     that.addFinalFunc(tempItem);
                // }
                that.calFunc();
            })
        })
    },
    addFinalFunc(item){
        console.log('---新--',item);
        var that = this;
        var tempList = that.data.defaultItemList;
        console.log('加---',tempList);
       
        for(var i = 0;i < tempList.length;i++){
            if(item.id == tempList[i].id){
                tempList[i].selectNum =  tempList[i].selectNum+1;
            }
        
        }

        that.setData({
            defaultItemList: tempList,
        })
    },
    minusFinalFunc(item){
        console.log('---2新--',item);
        var that = this;
        var tempList = that.data.defaultItemList;
       
        for(var i = 0;i < tempList.length;i++){
            if(item.id == tempList[ i].id){
                tempList[i].selectNum =  tempList[i].selectNum-1;
            }
         
        }
        that.setData({
            defaultItemList: tempList,
        })
    },
    // 店铺详情
    shopInfo() {
        var that = this
        var tempJson = {
            storeId: that.data.storeId,
            xpoint: this.data.lat,
            ypoint: this.data.lon,
            xcFlag: '0' //是否含有携程门票 0不含有
        }
        common.get('/store/mainPageInfo', tempJson, res => {
            for (let i = 0; i < res.data.couponList.length; i++) {
                that.setData({
                    industryType: res.data.store.industryType
                })
            }
            if (res.data.commentList) {
                for (var i = 0; i < res.data.commentList.length; i++) {
                    res.data.commentList[i].addTime = that.time(res.data.commentList[i].addTime)
                }
            }
            
            var tempList = res.data.itemCatList2.storeCatList;
            console.log('主页里---',tempList);
            console.log('角标i里---',this.data.leftBadgeList);
            for(var i = 0;i<tempList.length;i++ ){
                for(var j = 0;j < this.data.leftBadgeList.length;j++){
                    if(parseInt(this.data.leftBadgeList[j].storeCid)==tempList[i].id){
                        tempList[i].num = this.data.leftBadgeList[j].num;
                    }
                }
            }
            console.log('aaa主页里---',tempList);
            this.setData({

                commentList: res.data.commentList,

                activeId: res.data.itemCatList2.storeCatList.length > 0 ? res.data.itemCatList2.storeCatList[0].id : '',
                couponList: res.data.couponList,
                shopInfo: res.data,

            }, () => {
                

            })
        })
    },
    calFunc(){
        var that = this;
         // 计算右侧商品高度
        wx.createSelectorQuery().selectAll('.cessss').boundingClientRect(function (rect) {//selectAll会选择所要含有该类名的盒子
        }).exec(function (res) {
            console.log(res,"454444444s")
            that.heightArry(res)
        })
        // console.log(res.data.itemCatList2.defaultItemList)
        // this.changeCategory(that.data.activeId)
    },
    toArticleDetail(e) {
        const item = e.currentTarget.dataset.item
        wx.navigateTo({
            url: '/pages/discovery/articleDetail/index?id=' + item.id +
                '&storeName=' + item.storeName +
                '&title=' + item.title +
                '&createTime=' + item.createTime +
                '&storeImg=' + item.storeImg
        })
    },

    queryCollection() {
        var that = this
        var tempJson = {
            token: that.data.token,
            userId: that.data.userInfo.id,
            storeId: that.data.storeId
        };
        common.post("/store/favo/collected", tempJson, function (res) {
            // 当前接口200是关注，非200是未关注
            that.setData({
                isCollected: res.data
            })
        });
    },
    // 是否收藏
    clickCollect() {
        let that = this
        let param = that.data.isCollected ? 'delete' : 'add'
        var tempJson = {
            token: that.data.token,
            userId: that.data.userInfo.id,
            storeId: that.data.storeId
        };
        common.post("/store/favo/" + param, tempJson, function (res) {
            res.status == 200 && that.queryCollection()
        })
    },

    // 商品接口
    // changeCategory(idx) {
    //     this.setData({
    //         isLoading: true
    //     })
    //     const that = this
    //     const tempJson = {
    //         storeCid: idx,
    //         storeId: that.data.storeId,
    //         token: that.data.token,
    //         userId: that.data.userInfo.id
    //     }
    //     common.post('/store/mainPageInfo/storeCid', tempJson, function (res) {
    //         if (res.status === 200) {
    //             that.setData({
    //                 defaultItemList: res.data.data
    //             }, () => {

    //             })
    //         } else {
    //             that.setData({
    //                 defaultItemList: []
    //             })
    //             common.showRequestErrMsg(res)
    //         }
    //     }, function () {
    //         that.setData({
    //             isLoading: false
    //         })
    //     })
    // },
    // 时间戳
    time(time) {
        return common.dateFormat('yyyy-MM-dd HH:mm', time)
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let screenHeight = wx.getSystemInfoSync().windowHeight
        let okHeight = (screenHeight - 88 - 110 - 80 - 65)
        const that = this
        this.setData({
            toView: 'a1',
        })
        // 返回按钮
        let capsule = wx.getMenuButtonBoundingClientRect()
        this.setData({
            okHeight,
            height: capsule.height,
            top: capsule.top,
            storeId: options.id ? options.id : 5004,
        })
        // 用户信息
        common.getLocalUserInfo((success, data) => {
            if (success) {
                this.setData({
                    userInfo: data.user,
                    token: data.token,
                    openid: data.openid,
                }, () => {
                    this.clickCollect()  //是否收藏
                    this.gong(true)
                    this.queryCollection()
                    this.getCartNum(true)
                    that.getStoreCoupons(options.id, true)
                    that.getCardForTakeawayFunc(options.id, true)
                    
                })
            }
        }, true)

        // 定位
        that.getLocation()
    },
    // 获取当前定位
    getLocation() {
        
        app.getLocation(
            (data) => {
                this.setData({
                    lon: data.longitude,
                    lat: data.latitude
                }, () => {
                    this.shopInfo()
                    this.getHasSelectShopItemIdAndCountFunc();
         
                    // this.getLeftBadgeNum(true)
                   
                })
            },
            (err) => {
                // 定位失败回调
                this.setData({
                    refreshing: false
                })
            })
    },

    getHasSelectShopItemIdAndCountFunc(tempItem,type) {
        const that = this
        let tempJson = {
            storeId: that.data.storeId,
            userId: that.data.userInfo.id,
            token: that.data.token
        }
        console.log('type---',type);
        common.wxRequest('/cart/listByStore', 'post', tempJson, 'application/x-www-form-urlencoded', function (res) {
            console.log('获取已选商品的id和个数',res);
            if (res.status === 200) {
          
                that.setData({
                    getHasSelectShopItemIdAndCountList:res.data.list
                },()=>{
                    // 获取左边类目及个数、右边列表、给历史选中增加selectNum和selectCardId属性
                    that.getUserSelectInfo(tempItem,type);
                })
              
            
            } else {

                that.setData({
                    getHasSelectShopItemIdAndCountList:[]
                },()=>{
                    // 获取左边类目及个数、右边列表、给历史选中增加selectNum和selectCardId属性
                    that.getUserSelectInfo(tempItem,type);
                })
              

      
             
            }
        }, () => {
            that.setData({
                isShowLoader: false  //购物车加载
            })
        })
    },
    // 右侧商品的高度
    heightArry(res) {
        let h = 0;
        let heightArr = [];
        res[0].forEach((item) => {
            h += item.height;
            heightArr.push(h);
        })
        this.setData({ heightArr: heightArr })
    },
    // 滚动事件
    Right_Scroll(e) {
        const those = this
        if (!those.data.clickShow) {
            let scrollHeight = e.detail.scrollTop;
            let index = this.calculateIndex(this.data.heightArr, scrollHeight);
            console.log(index)
            this.setData({
                activeId: those.data.defaultItemList[index].storeCid
            }, () => {
            })
        }
        this.setData({
            clickShow: false
        })

    },
    // 计算左边选中的下标
    calculateIndex(arr, scrollHeight) {
        let index = '';
        for (let i = 0; i < arr.length; i++) {
            if (scrollHeight >= 0 && scrollHeight < arr[0]) {
                index = 0;
            } else if (scrollHeight >= arr[i - 1] && scrollHeight < arr[i]) {
                index = i;
            }
        }
        return index;
    },
    // 二级分类点击
    clickItem(e) {
        console.log('eee-----',e.currentTarget.dataset.id);
        const that = this
        this.setData({
            activeId: e.currentTarget.dataset.id,
            toView: e.currentTarget.dataset.id,
            clickShow: true
        }, () => {

            // that.changeCategory(e.currentTarget.dataset.id)
            //    const index =  that.data.defaultItemList.findIndex((i)=>{
            //          return i.storeCid === this.data.activeId
            //     })
            //     console.log(index)
            //     console.log(this.data.heightArr)
        })
    },
    // tabs切换
    click_item(e) {
        let index = e.currentTarget.dataset.index
        this.setData({
            actIndex: index
        })
    },
    // 点击收藏
    clickCollect() {
        let that = this
        let param = that.data.isCollected ? 'delete' : 'add'
        var tempJson = {
            token: that.data.token,
            userId: that.data.userInfo.id,
            storeId: that.data.storeId
        };
        common.post("/store/favo/" + param, tempJson, function (res) {
            res.status == 200 && that.queryCollection()
        })

    },
    // 选规格
    go_guige(e) {
        this.setData({
            guigeShow: true,
  
        })
        this.clickGetDishAttrList(e)
    },
    onClose() {
        this.setData({
            guigeShow: false
        });
    },
    // 商品规格
    clickGetDishAttrList(e) {
        let that = this
        let { id, item } = e.currentTarget.dataset
        let tempJson = {
            itemId: id,

        }
        that.setData({
            itemId: id,
            goodsNei: item
        })
        common.post("/item/getDishAttrList", tempJson, function (res) {
            console.log(res,"545466666222222222")
            let checkedStr = '';
            for (let i = 0; i < res.data.length; i++) {
                if (i !== res.data.length - 1) {// 不是最后一个，就拼接/
                    checkedStr = checkedStr + res.data[i].attrValueList[0].attrValue + '/'
                } else {// 最后一个，不拼接/
                    checkedStr = checkedStr + res.data[res.data.length - 1].attrValueList[0].attrValue
                }

            }
            var tempList = res.data;
            for(var i = 0;i < tempList.length;i++){
                var twoList = tempList[i];
                for(var j =0;j < twoList.attrValueList.length;j++){
                    twoList.attrValueList[j].select = false;
                }
            }
            console.log('---checkedStr--',checkedStr);
            that.setData({
                allAttrValueList: tempList,
                checkedAttr: checkedStr
            },()=>{
                console.log('----++====',tempList);
            })
        })
    },
    

    clickGoodsCount(e) {
        console.log('数量---',e.detail);
        this.setData({
            goodsCount: e.detail,
        }, () => {
            // this.submitAddCart()
        })
    },
    // 添加购物车
    submitAddCart() {
        const that = this
        const num = this.data.goodsCount
        const itemId = this.data.itemId
        if (!num) {
            common.showToast('没有添加数量')
            return
        }
        console.log('suoyoushuj---',that.data.allAttrValueList);
        // < checkedAttr that.data.allAttrValueList
        var checkedStr = '';
        for(var i = 0;i < that.data.allAttrValueList.length;i++){
            var twoList = that.data.allAttrValueList[i];
            for(var j =0;j < twoList.attrValueList.length;j++){
                if(twoList.attrValueList[j].select == true){
                    checkedStr = checkedStr + twoList.attrValueList[j].attrValue + '/'
                }
              
            }
        }
        let tempJson = {
            // dishFlavor: that.data.checkedAttr,
            dishFlavor:checkedStr?checkedStr.slice(0, -1):'',
            userId: that.data.userInfo.id,
            token: that.data.token,
            itemId,
            num
        }
        common.wxRequest('/cart/add', 'post', tempJson, 'application/x-www-form-urlencoded', function (res) {
            if (res.status === 200) {
                that.closeAddCart()
                that.getCartNum()  //获取
                that.getHasSelectShopItemIdAndCountFunc();
                // that.getLeftBadgeNum();
                that.setData({
                    goodsCount: 1,
                })
                common.showToast('添加成功!')
                // wx.showToast({
                //     title: '添加成功!',
                // })
            } else {
                wx.showToast({
                    icon: 'loading',
                    title: res.msg ? res.msg : '添加失败',
                })
            }
        })
    },
    normalDeleteCardFunc(num, cartId, item) {
        const that = this
        this.setData({
            isShowLoader: true
        })
        let tempJson = {
            itemId: item.id,
            token: that.data.token,
            cartId,
            num,
            userId: that.data.userInfo.id,
        }
        common.wxRequest('/cart/updateOneByCartId', 'POST', tempJson, 'application/x-www-form-urlencoded', function (res) {
            if (res.status === 200) {
                that.getCartNum()
                that.getHasSelectShopItemIdAndCountFunc(item,'minus');
                // var tempList = that.data.defaultItemList;
                // for(var i = 0;i < tempList.length;i++){
                //     if(itemId == tempList[ i].id){
                //         tempList[i].selectNum =  tempList[i].selectNum-1;
                //     }
                 
                // }
                // that.setData({
                //     defaultItemList: tempList,
                // })


            } else {
                wx.showToast({
                    title: res.msg ? res.msg : '添加失败',
                })
            }
        })
    },


    normalAddCardFunc(tempItem,num) {
        const that = this

 
        let tempJson = {
   
            dishFlavor:'',
            userId: that.data.userInfo.id,
            token: that.data.token,
            itemId:tempItem.id,
            num
        }
        common.wxRequest('/cart/add', 'post', tempJson, 'application/x-www-form-urlencoded', function (res) {

            
            if (res.status === 200) {

               that.getHasSelectShopItemIdAndCountFunc(tempItem,'add');
  
                that.closeAddCart()
                that.getCartNum()  //获取
                // that.getLeftBadgeNum();
                that.setData({
                    goodsCount: 1,
                })
                common.showToast('添加成功!')
                // wx.showToast({
                //     title: '添加成功!',
                // })
            } else {
                wx.showToast({
                    icon: 'loading',
                    title: res.msg ? res.msg : '添加失败',
                })
            }
        })
    },


    closeAddCart() {
        this.setData({
            guigeShow: false
        })
    },
    // 点击购物车
    click_shoppcar() {
        this.setData({
            shopCarShow: true,
        }, () => {
            this.getCartNum()
        })
    },
    // 清空购物车    userId  cartIds  删除或者多个
    clearCart() {
        const that = this
        let arrList = []
        for (let i = 0; i < that.data.cartList.length; i++) {
            arrList.push(that.data.cartList[i].id)
        }

        this.setData({
            isShowLoader: true
        })
        let tempJson = {
            cartIds: arrList.toString(),
            userId: that.data.userInfo.id,
            token: that.data.token
        }
        // that.setData({
        //     isShowLoader: false  //购物车加载
        // })
        if(!arrList.toString()){
            

            wx.showToast({
                icon: 'none',
                title: '您还未添加商品到购物车~',
            })
            return;
        }
        common.wxRequest('/cart/deleteByCartId ', 'post', tempJson, 'application/x-www-form-urlencoded', function (res) {
            if (res.status === 200) {
                // that.onCloses()
                that.getCartNum()
                that.getHasSelectShopItemIdAndCountFunc();
            } else {
                wx.showToast({
                    title: res.msg ? res.msg : '添加失败',
                })
            }
        })
    },
    // 返回上页面
    goBack() {
        const pages = getCurrentPages();
        const prevPage = pages[pages.length - 2]; //上一个页面
        // 从朋友圈进入的时候，页面栈为空，这里需要判断是否有上个页面
        if (prevPage) {
            wx.navigateBack({
                delta: 1
            })
        } else {
            wx.redirectTo({
                url: '/pages/index/index',
            })
        }
    },
    // 购物车关闭
    onCloses() {
        this.setData({
            shopCarShow: false
        })
    },
    //购物车减少一
    onminus(e) {
        let item = e.currentTarget.dataset.item
        let cartId = item.id
        console.log(item, "lllllllllllllllllllllllllllllllllllllll")
        this.changeCartNum(-1, cartId, item.itemId)

    },
    //  购物车增加1
    onplus(e) {
        let { index, item } = e.currentTarget.dataset
        let cartId = item.id
        this.changeCartNum(1, cartId, item.itemId)
    },
    //购物车加一
    changeCartNum(num, cartId, itemId) {
        const that = this
        this.setData({
            isShowLoader: true
        })
        let tempJson = {
            itemId: itemId,
            token: that.data.token,
            cartId,
            num,
            userId: that.data.userInfo.id,
        }
        common.wxRequest('/cart/updateOneByCartId', 'POST', tempJson, 'application/x-www-form-urlencoded', function (res) {
            if (res.status === 200) {
                that.getCartNum()
                that.getHasSelectShopItemIdAndCountFunc();
            } else {
                wx.showToast({
                    title: res.msg ? res.msg : '添加失败',
                })
            }
        })
    },
    // 购物车输入改变
    onblur(e) {
        const that = this
        let { item } = e.currentTarget.dataset
        let num = e.detail.value
        let cartId = item.id
        that.inputCartNum(num, cartId, item.itemId)

    },
    //  输入input改变     userId cartId num   修改数量
    inputCartNum(num, cartId) {
        const that = this
        this.setData({
            isShowLoader: true
        })
        let tempJson = {
            cartId,
            num,
            userId: that.data.userInfo.id,
            token: that.data.token
        }
        common.wxRequest('/cart/updateNumByCartId', 'post', tempJson, 'application/x-www-form-urlencoded', function (res) {
            if (res.status === 200) {
                that.onCloses()
                that.getCartNum()
            } else {
                wx.showToast({
                    title: res.msg ? res.msg : '添加失败',
                })
            }
        })
    },
    //    立即结算
    go_balance() {
        // return
        if (this.data.cartNum == 0) {
            return
        }
        wx.navigateTo({
            url: `/packageC/pages/takeoutOrder/takeoutOrder?storeId=${this.data.storeId}&totalPrice=${this.data.totalPrice}&storeId=${this.data.storeId}`,
        })
    },
    // 列表触底
    loadMore() {
        this.getStoreCoupons(false)
    },
    minusFunc(e){
        // selectCardId
        var item = e.currentTarget.dataset.item;
        this.normalDeleteCardFunc(-1, item.selectCardId, item) 
    },
    addFunc(e){
        console.log("++++",e.currentTarget.dataset);
        var item = e.currentTarget.dataset.item;
        this.normalAddCardFunc(item, 1)

    },
    click_oneId(e) {
        let that = this
        // console.log('----',e.currentTarget.dataset.item.attrValueList);
        // console.log('----',e.currentTarget.dataset.index);
        // console.log('++++',e.currentTarget.dataset.item[e.currentTarget.dataset.index]);
        // var currentIndex = e.currentTarget.dataset.index;
        // var currentItem = e.currentTarget.dataset.item[currentIndex]


        console.log('----',e.currentTarget.dataset.index);
        console.log('++++',e.currentTarget.dataset.item);

        var currentItem = e.currentTarget.dataset.item;

      
        var tempList = that.data.allAttrValueList;
        for(var i = 0;i < tempList.length;i++){
            var twoList = tempList[i];
            for(var j =0;j < twoList.attrValueList.length;j++){
                // twoList.attrValueList[j].select = false;
                if(twoList.attrValueList[j].id == currentItem.id){
                    if(twoList.attrValueList[j].attrId == currentItem.attrId){
                        for(var m =0;m < twoList.attrValueList.length;m++){
                            twoList.attrValueList[m].select = false;
                        }
                        twoList.attrValueList[j].select = true;
                    }
                    
                }
            }
        }


        if(currentItem.attrId){

        }
        this.setData({
            // allAttrValueList:that.data.allAttrValueList,
            allAttrValueList:tempList,
            oneId:currentItem.id,
        },()=>{
            console.log('oneId---',that.data.oneId);
            console.log('最新---',that.data.allAttrValueList);
        })
        return;
        let {
            couponid
        } = e.currentTarget.dataset
        let tempJson = {
            userId: that.data.userInfo.id,
            discountCouponId: couponid,
            source: 1, // 1为手动领取，2为系统群发
            token: that.data.token
        }

    },
    onStoreCouponosClose() { this.setData({ showStoreCoupons: false }) },

    inputChange1: function (options) {
        //获取输入框输入的内容
        let value = options.detail.value;
        console.log("输入框输入的内容是 " + value)
        this.setData({
            rightShopCount:value
        })
      },
      getCardForTakeawayFunc(idx){
        
        var that = this
        let tempJson = {
            storeId: idx,
        
        }

        common.post('/userAnnualCard/getCardForTakeawayRec', tempJson, function (res) {
            console.log('年5卡会员',res);
            if (res.status === 200) {
                that.setData({
                    cardVipJson:res.data,
                })
                if(res.data){
                    that.isPayFunc(res.data.id);
                }
            
            } else {
                // common.showRequestErrMsg(res)
            }
        }, function () {
           
        })
    },
     // 判断是否支付
  isPayFunc(idx) {
    var that = this
    common.get('/userAnnualCard/checkUserBoughtCard', {
        userId: this.data.userInfo.id,
        cardId: idx,
        token: this.data.token
    }, res => {
        console.log(res)

        that.setData({
            
            hasBuy:res.status === 1?true:false,
        },()=>{
            console.log('ssss---',that.data.hasBuy);
        })
   
    })
},

})